// ==UserScript==
// @name 139.xq
// @author wgu
// @description  139xq
// @include http://xq.139life.com/frontSurvey/answer.jsp*
// @include http://xq.139life.com/frontSurvey/success.jsp*
// ==/UserScript==
var xqDB = gw.db('xqdt.sqlite'),req=gw.req();
if(location.href.indexOf('/frontSurvey/answer.jsp')!=-1){
	xqDB.open();
	var r=xqDB.getData("select * from xq where q="+document.myform.questionId.value,[1,0,0,0]);
	xqDB.close();
	
	_oldsubmit=document.myform.submit;
	function my(){
		_oldsubmit.call(document.myform);
	}
	if(r.length==0){
		document.myform.submit=function(){
			var a=[];
			a.push(document.myform.nextQuestionId.value);
			a.push(document.myform.answer.value);
			a.push(document.myform.questionItem.value);
			a.push(document.myform.subjectId.value);
			xqDB.open();
			try{
				console.log("INSERT INTO xq VALUES ("+document.myform.questionId.value+",'"+a.join("','")+"');");
				xqDB.exeSQL("INSERT INTO xq VALUES ("+document.myform.questionId.value+",'"+a.join("','")+"');");
			}catch(err){}
			xqDB.close();
			_oldsubmit.call(document.myform);
		}
	}else{
		console.log(r);
		document.myform.nextQuestionId.value=r[0][1];
		document.myform.answer.value=r[0][2];
		document.myform.questionItem.value=r[0][3];
		xqDB.open();
		try{
		 xqDB.exeSQL("UPDATE xq set subjectId='"+document.myform.subjectId.value+"' where q="+document.myform.questionId.value);
		}catch(err){}
		xqDB.close();
		setTimeout(my,2000);
		//_oldsubmit.call(document.myform);
	}
}else if(location.href.indexOf('/frontSurvey/success.jsp')!=-1){
	xqDB.open();
	req.open('GET','http://xq.139life.com/frontSurvey/list.jsp?pageIndex=1&orderBy=3',false);
	req.send();
	var match=req.responseText.match(/question_view.jsp\?subjectId=\d+/g);
	match.forEach(function(v,i){
		match[i]=v.replace('question_view.jsp?subjectId=','');
	})
	var r=xqDB.getData("select subjectId from xq where subjectId in ('"+match.join("','")+"')",[0]);
	if(r.length==0){
		req.open('GET','http://xq.139life.com/frontSurvey/list.jsp?pageIndex=2&orderBy=3',false);
		req.send();
		var match=req.responseText.match(/question_view.jsp\?subjectId=\d+/g);
		match.forEach(function(v,i){
			match[i]=v.replace('question_view.jsp?subjectId=','');
		})
		var r=xqDB.getData("select subjectId from xq where subjectId in ('"+match.join("','")+"')",[0]);
		if(r.length==0){
			alert('OK');
		}else{
			window.location="http://xq.139life.com/frontSurvey/answer.jsp?subjectId="+r[0][0];
		}
	}else{
		window.location="http://xq.139life.com/frontSurvey/answer.jsp?subjectId="+r[0][0];
	}
	xqDB.close();
	
}

	